package com.example.gitclient.ui;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.gitclient.R;
import com.example.gitclient.git.GitManager;
import com.example.gitclient.model.Repository;
import com.example.gitclient.utils.RepositoryManager;

import org.eclipse.jgit.api.errors.GitAPIException;

import java.io.IOException;

/**
 * 仓库详情界面，显示仓库信息和提供Git操作
 */
public class RepositoryActivity extends AppCompatActivity {
    private TextView tvRepositoryName;
    private TextView tvCurrentBranch;

    private Repository repository;
    private GitManager gitManager;
    private RepositoryManager repositoryManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repository);

        // 初始化视图
        tvRepositoryName = findViewById(R.id.tvRepositoryName);
        tvCurrentBranch = findViewById(R.id.tvCurrentBranch);
        Button btnBranches = findViewById(R.id.btnBranches);
        Button btnCommits = findViewById(R.id.btnCommits);
        Button btnFiles = findViewById(R.id.btnFiles);
        Button btnPull = findViewById(R.id.btnPull);
        Button btnCommit = findViewById(R.id.btnCommit);
        Button btnPush = findViewById(R.id.btnPush);

        // 获取仓库路径
        String repositoryPath = getIntent().getStringExtra("repository_path");
        if (repositoryPath == null) {
            Toast.makeText(this, R.string.repository_not_found, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化仓库管理器
        repositoryManager = new RepositoryManager(this);

        // 加载仓库
        loadRepository(repositoryPath);

        // 设置按钮点击事件
        btnBranches.setOnClickListener(v -> openBranchActivity());
        btnCommits.setOnClickListener(v -> openCommitHistoryActivity());
        btnFiles.setOnClickListener(v -> openFileExplorerActivity());
        btnPull.setOnClickListener(v -> pullChanges());
        btnCommit.setOnClickListener(v -> showCommitDialog());
        btnPush.setOnClickListener(v -> showPushDialog());
    }

    /**
     * 加载仓库
     * @param repositoryPath 仓库路径
     */
    private void loadRepository(String repositoryPath) {
        // 查找仓库
        for (Repository repo : repositoryManager.getRepositories()) {
            if (repo.getPath().equals(repositoryPath)) {
                repository = repo;
                break;
            }
        }

        if (repository == null) {
            Toast.makeText(this, R.string.repository_not_found, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 打开Git仓库
        try {
            gitManager = new GitManager(repository);
            updateUI();
        } catch (IOException e) {
            Toast.makeText(this, getString(R.string.failed_to_open_repository) + ": " + e.getMessage(), Toast.LENGTH_LONG).show();
            finish();
        }
    }

    /**
     * 更新UI
     */
    private void updateUI() {
        tvRepositoryName.setText(repository.getName());
        tvCurrentBranch.setText(getString(R.string.current_branch) + ": " + repository.getCurrentBranch());
    }

    /**
     * 打开分支界面
     */
    private void openBranchActivity() {
        Intent intent = new Intent(this, BranchActivity.class);
        intent.putExtra("repository_path", repository.getPath());
        startActivity(intent);
    }

    /**
     * 打开提交历史界面
     */
    private void openCommitHistoryActivity() {
        Intent intent = new Intent(this, CommitHistoryActivity.class);
        intent.putExtra("repository_path", repository.getPath());
        startActivity(intent);
    }

    /**
     * 打开文件浏览界面
     */
    private void openFileExplorerActivity() {
        Intent intent = new Intent(this, FileExplorerActivity.class);
        intent.putExtra("repository_path", repository.getPath());
        startActivity(intent);
    }

    /**
     * 拉取更改
     */
    private void pullChanges() {
        if (repository.getRemoteUrl() == null) {
            Toast.makeText(this, R.string.no_remote_repository, Toast.LENGTH_SHORT).show();
            return;
        }

        // 显示用户名密码对话框
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_credentials, null);
        EditText etUsername = dialogView.findViewById(R.id.etUsername);
        EditText etPassword = dialogView.findViewById(R.id.etPassword);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.enter_credentials)
                .setView(dialogView)
                .setPositiveButton(R.string.pull, (dialog, which) -> {
                    String username = etUsername.getText().toString().trim();
                    String password = etPassword.getText().toString().trim();

                    if (username.isEmpty() || password.isEmpty()) {
                        Toast.makeText(this, R.string.please_enter_credentials, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // 显示进度对话框
                    AlertDialog progressDialog = new AlertDialog.Builder(this)
                            .setTitle(R.string.pulling_changes)
                            .setMessage(R.string.please_wait)
                            .setCancelable(false)
                            .show();

                    // 在后台线程中拉取更改
                    new Thread(() -> {
                        try {
                            gitManager.pull(username, password);

                            // 在UI线程中更新界面
                            runOnUiThread(() -> {
                                progressDialog.dismiss();
                                Toast.makeText(this, R.string.pull_successful, Toast.LENGTH_SHORT).show();
                                updateUI();
                            });
                        } catch (GitAPIException e) {
                            // 在UI线程中显示错误
                            runOnUiThread(() -> {
                                progressDialog.dismiss();
                                Toast.makeText(this, getString(R.string.pull_failed) + ": " + e.getMessage(), Toast.LENGTH_LONG).show();
                            });
                        }
                    }).start();
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    /**
     * 显示提交对话框
     */
    private void showCommitDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_commit, null);
        EditText etCommitMessage = dialogView.findViewById(R.id.etCommitMessage);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.commit_changes)
                .setView(dialogView)
                .setPositiveButton(R.string.commit, (dialog, which) -> {
                    String message = etCommitMessage.getText().toString().trim();

                    if (message.isEmpty()) {
                        Toast.makeText(this, R.string.please_enter_commit_message, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    try {
                        // 添加所有更改到暂存区
                        gitManager.addAllFiles();
                        // 提交更改
                        gitManager.commit(message);
                        Toast.makeText(this, R.string.commit_successful, Toast.LENGTH_SHORT).show();
                    } catch (GitAPIException e) {
                        Toast.makeText(this, getString(R.string.commit_failed) + ": " + e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    /**
     * 显示推送对话框
     */
    private void showPushDialog() {
        if (repository.getRemoteUrl() == null) {
            Toast.makeText(this, R.string.no_remote_repository, Toast.LENGTH_SHORT).show();
            return;
        }

        // 显示用户名密码对话框
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_credentials, null);
        EditText etUsername = dialogView.findViewById(R.id.etUsername);
        EditText etPassword = dialogView.findViewById(R.id.etPassword);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.enter_credentials)
                .setView(dialogView)
                .setPositiveButton(R.string.push, (dialog, which) -> {
                    String username = etUsername.getText().toString().trim();
                    String password = etPassword.getText().toString().trim();

                    if (username.isEmpty() || password.isEmpty()) {
                        Toast.makeText(this, R.string.please_enter_credentials, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // 显示进度对话框
                    AlertDialog progressDialog = new AlertDialog.Builder(this)
                            .setTitle(R.string.pushing_changes)
                            .setMessage(R.string.please_wait)
                            .setCancelable(false)
                            .show();

                    // 在后台线程中推送更改
                    new Thread(() -> {
                        try {
                            gitManager.push(username, password);

                            // 在UI线程中更新界面
                            runOnUiThread(() -> {
                                progressDialog.dismiss();
                                Toast.makeText(this, R.string.push_successful, Toast.LENGTH_SHORT).show();
                            });
                        } catch (GitAPIException e) {
                            // 在UI线程中显示错误
                            runOnUiThread(() -> {
                                progressDialog.dismiss();
                                Toast.makeText(this, getString(R.string.push_failed) + ": " + e.getMessage(), Toast.LENGTH_LONG).show();
                            });
                        }
                    }).start();
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (gitManager != null) {
            gitManager.close();
        }
    }
}